﻿namespace EasyWeb.Test
{
    using System.ComponentModel.Composition;
    using System.Linq;
    using System.Threading.Tasks;
    using EasyWeb.Data;
    using EasyWeb.Extensions;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class EWSelectionDefinition_Test : BaseTest
    {
        [Import(typeof(IEWSelectionDefinitionDao))]
        public IEWSelectionDefinitionDao SelectionDefintionDao;

        [Import(typeof(IEWSelectionItemDefinitionDao))]
        public IEWSelectionItemDefinitionDao SelectionItemDefintionDao;

        [TestMethod]
        public async Task All_Test()
        {
            await Create("test1", new EWSelectionItemDefinition(), new EWSelectionItemDefinition());
            await Create("test2", new EWSelectionItemDefinition());
            await Create("test3");

            var selections = await this.SelectionDefintionDao.SelectAsync();

            var test1 = selections.SingleOrDefault(e => e.InternalName == "test1");
            Assert.IsNotNull(test1);
            Assert.AreEqual(2, test1.SelectionItems.Count);

            var test2 = selections.SingleOrDefault(e => e.InternalName == "test2");
            Assert.IsNotNull(test2);
            Assert.AreEqual(1, test2.SelectionItems.Count);

            var test3 = selections.SingleOrDefault(e => e.InternalName == "test3");
            Assert.IsNotNull(test3);
            Assert.AreEqual(0, test3.SelectionItems.Count);
        }

        [TestInitialize]
        public override void TestInitialize()
        {
            base.TestInitialize();

            EWExtensionManager.CompositionContainer.SatisfyImportsOnce(this);
        }

        private async Task Create(string name, params EWSelectionItemDefinition[] items)
        {
            var selection = new EWSelectionDefinition()
            {
                InternalName = name,
                DisplayName = CreateText(),
            };

            await this.SelectionDefintionDao.CreateAsync(selection);

            if (items != null)
            {
                for (int i = 0; i < items.Length; i++)
                {
                    var item = items[i];
                    item.Key = string.Format("Key{0}", i);
                    item.Value = CreateText();
                    item.SelectionDefinitionId = selection.Id;
                    await this.SelectionItemDefintionDao.CreateAsync(item);
                }
            }
        }

        private static EWText CreateText()
        {
            var text = new EWText();
            text.Values.Add(new EWTextValue("en", "v1"));
            text.Values.Add(new EWTextValue("zh-Hans", "v2"));

            return text;
        }
    }
}
